<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>添加新闻</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }

        .divX {
            position: absolute;
            top: 0px;
            right: 0px;
            text-align: right;
            padding-right: 3px;
            z-index: 200;
            -moz-border-radius: 20px;
            -webkit-border-radius: 20px;
            line-height: 10px;
            font-weight: bold;
            cursor: pointer;
            font-size: 10px;
        }

        .divimg {
            max-height: 220px;
            /* height: px; */
            width: 256px;
            max-width: 258px;
            background-color: #fff;
            border: 1px dashed #e6e6e6;
            position: relative;
            text-align: center;
            font-size: 20px;
        }
    </style>
</head>

<body>
    <div class="layui-form layuimini-form">
        <div class="layui-form-item">
            <label class="layui-form-label required">新闻标题：</label>
            <div class="layui-input-block">
                <input type="text" name="title" lay-verify="required" lay-reqtext="不能为空" placeholder="填写新闻标题" value=""
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">作者：</label>
            <div class="layui-input-block">
                <input type="text" name="author" lay-verify="required" lay-reqtext="不能为空" placeholder="填写作者姓名" value=""
                    class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">新闻内容：</label>
            <div id="editor" class="layui-input-block">

            </div>
        </div>
        <!-- 传递上图片的地址 -->
        <input type="hidden" name="src" value="">
        <div class="layui-form-item">
            <label class="layui-form-label">新闻封面图片：</label>
            <div class="layui-upload-drag" id="test10">
                <div class="layui-progress" lay-filter="lodingdemo" lay-showpercent="true">
                    <div class="layui-progress-bar" lay-percent="0%"></div>
                </div>
                <i class="layui-icon"></i>
                <p>点击上传，或将文件拖拽到此处</p>
                <hr />
            </div>
            <div class="layui-hide layui-input-block" id="uploadDemoView">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn " id="uploadBtn" lay-submit="">开始上传</button>
            </div>
        </div>
        <div class="layui-form-item layui-hide" id="showSwitch">
            <label class="layui-form-label">是否加入轮播图：</label>
            <div class="layui-input-block">
                <input type="checkbox" name="open" lay-skin="switch" id="switch" lay-filter="switchTest"
                    lay-text="加入|不加入">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认发布</button>
            </div>
        </div>
    </div>
    <!-- 注意， 只需要引用 JS，无需引用任何 CSS ！！！-->
    <script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
    <script type="text/javascript">
        layui.use(['layer', 'wangEditor', 'upload', 'form', 'element', 'cookie'], function () {
            var $ = layui.jquery,
                layer = layui.layer,
                wangEditor = layui.wangEditor,
                upload = layui.upload,
                form = layui.form,
                element = layui.element,
                cookie = layui.cookie;
            // wangEditor配置
            var editor = new wangEditor('#editor');
            editor.customConfig.uploadImgServer = "../../upload/inner-images";
            editor.customConfig.uploadFileName = 'image';
            editor.customConfig.pasteFilterStyle = false;
            editor.customConfig.uploadImgMaxLength = 5;
            editor.customConfig.uploadImgHooks = {
                // 上传超时
                timeout: function (xhr, editor) {
                    layer.msg('上传超时！')
                },
                // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
                customInsert: function (insertImg, result, editor) {
                    if (result.code == 200) {
                        var url = result.data.url;
                        url.forEach(function (e) {
                            insertImg(e);
                        })
                    } else {
                        layer.msg(result.message);
                    }
                }
            };
            // 图片上传成功后的地址
            var url=null;
            var content=null;
            // 将新闻内容存入
            editor.customConfig.onchange = function (newHtml) {
                content=newHtml;
            }
            editor.customConfig.customAlert = function (info) {
                layer.msg(info);
            };
            // 配置菜单栏
            editor.customConfig.menus = [
                'head',
                'bold',
                'fontSize',
                'fontName',
                'italic',
                'underline',
                'strikeThrough',
                'indent',
                'lineHeight',
                'foreColor',
                'backColor',
                'link',
                'list',
                'todo',
                'justify',
                'quote',
                'emoticon',
                'image',
                'splitLine',
                'undo',
                'redo',
            ]
            editor.create();
            // 上传封面图片
            var flag = 0;
            var num = 0;
            var uploadMain = upload.render({
                elem: '#test10',
                url: '/upload/news',
                accept: 'images',
                multiple: true,
                acceptMime: 'image/jpg,image/png,image/jpeg',
                choose: function (obj) { //选择后触发
                    var files = this.files = obj.pushFile();
                    var view = layui.$('#uploadDemoView');
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        var img = new Image();
                        img.src = result;
                        img.onload = function () { //初始化夹在完成后获取上传图片宽高，判断限制上传图片的大小。
                            // 判断出最长边和最短边
                            var width = img.width;
                            var height = img.height;
                            //  计算比例
                            var ratio = height / width;
                            // 四舍五入保留两位小数
                            ratio = ratio.toFixed(2);
                            if (ratio === '0.56') {
                                //满足条件调用上传方法
                                flag = 1;
                                var _html = $([
                                    '<div class="divimg" id="flag" style="float:left;color:red;">',
                                    '<img style="max-width: 190px;max-height:200px"  id="viewImg' +
                                    index + '" alt="上传成功后渲染"  src="' + result +
                                    '">', '</div>'
                                ].join(''));
                                layui.$('#uploadDemoView').removeClass('layui-hide');
                                view.removeClass('layui-hide');
                                view.append(_html);
                            } else {
                                delete files[index]; //删除对应文件
                                layer.alert("上传的图片宽高比例必须为16：9！", {
                                    icon: 5,
                                    title: "提示",
                                    offset: "auto",
                                    skin: 'layui-layer-molv'
                                });
                            }
                        }

                    });
                },
                auto: false //false将不触发before
                    //, bindAction: "#uploadBtn"
                    ,
                size: 3072 //单位kb
                    ,
                done: function (data) {
                    if (data.message) {
                        if (num === 0) {
                            // 将返回的图片地址存储
                            url=data.data.url;
                            // 图片上传成功后显示开关
                            $("#showSwitch").removeClass("layui-hide");
                            form.render();
                            layer.msg("上传成功！", {
                                icon: 1
                            });
                        }
                    }
                },
                progress: function (n, elem) {
                    var percent = n + '%' //获取进度百分比
                    element.progress('lodingdemo', percent); //可配合 layui 进度条元素使用
                }
            });
            // 默认不加入轮播图
            var is_using=0;
            //监听开关
            form.on('switch(switchTest)', function (data) {
                is_using = (this.checked) ? is_using = 1 : is_using = 0;
            });
            // 监听图片上传
            
            $("#uploadBtn").click(function () {
                if(flag===0){
                    return layer.msg("请先选择并上传图片！",{icon: 0});
                }
                uploadMain.upload();
                return false;
            })
            //监听提交
            form.on('submit(saveBtn)', function (data) {
                var result = data.field;
                result.is_using=is_using;
                result.url=url;
                result.content=content;
                result.role=$.cookie("role");
                result.staff_name=$.cookie("name");
                result = JSON.stringify(result);
                
                $.ajax({
                    url: "/news",
                    method: "POST",
                    data: result,
                    contentType: "application/json",
                    success: function (data) {
                        layer.msg("发布成功！",{icon:1});
                            setTimeout(function() {
                                var iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                                var str=($.cookie("role")==1)?str="/page/news-approved-admin.html":str="/page/news-not-approved-staff.html"
                                parent.location.href=str; 
                                num++;
                            },1500)

                    },
                    error: function (err) {
                        layer.msg("登录已过期，请重新登录", {
                            icon: 2
                        });
                    }
                })

                return false;
            });
        })
    </script>
</body>

</html>